<template>
  <section class="todoapp">
    <TodoHeader @addTodo="addTodoPar" />
    <TodoMain :arr="showList" @delTodo="delTodoPar" />
    <TodoFooter
      v-if="list.length > 0"
      :arr="list"
      @switchTodo="switchTodoPar"
      @clearTodo="clearTodoPar"
    />
  </section>
</template>

<script>
import "./assets/ccs/base.css";
import "./assets/ccs/index.css";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      parType: "all",
      list: JSON.parse(localStorage.getItem("todo")) || [
        { id: 100, name: "吃饭", isDone: true },
        { id: 201, name: "睡觉", isDone: false },
        { id: 103, name: "打豆豆", isDone: true },
      ],
    };
  },
  methods: {
    //添加
    addTodoPar(name) {
      const obj = {
        id: Date.now(), //时间戳
        name,
        isDone: false,
      };
      this.list.push(obj);
    },
    //删除
    delTodoPar(i) {
      if (confirm("确定要删除吗?")) {
        this.list.splice(i, 1);
      }
    },
    //切换
    switchTodoPar(switchType) {
      // console.log(switchType);
      this.parType = switchType;
    },
    //清空
    clearTodoPar() {
      this.list = this.list.filter((item) => item.isDone === false);
    },
  },
  computed: {
    // 切换列表功能
    showList() {
      if (this.parType === "all") {
        return this.list;
      } else if (this.parType === "no") {
        return this.list.filter((item) => item.isDone === false);
      } else {
        return this.list.filter((item) => item.isDone === true);
      }
    },
  },
  watch: {
    // 侦听数组变化
    list: {
      deep: true,
      handler(newVal) {
        localStorage.setItem("todo", JSON.stringify(newVal));
      },
    },
  },
};
</script>

<style>
</style>